﻿using Model=AG.Apps.Model;
using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;

namespace AG_Apps_Cloud_Services_WCF_Web_Role.Handlers
{
    /// <summary>
    /// Summary description for AdClick
    /// </summary>
    public class AdClick : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {

            Model.AGAppsEntities db = new Model.AGAppsEntities();

            string appCode = context.Request.QueryString["app"];
            int adId = System.Convert.ToInt32(context.Request.QueryString["ad"]);
            string username = context.Request.QueryString["user"];
            string source = context.Request.QueryString["source"];
            string language = context.Request.QueryString["language"];

            Model.App app = db.Apps.SingleOrDefault(a => a.AppCode == appCode);
            Model.Ad ad = db.Ads.SingleOrDefault(a => a.AdId == adId);

            if (app != null && ad != null)
            {
                Model.AdClick click = new Model.AdClick();

                click.App = app;
                click.Ad = ad;
                click.Time = DateTime.Now;
                click.Username = username;
                click.Source = source;
                click.Language = language;

                db.AdClicks.Add(click);
                db.SaveChanges();

                context.Response.Redirect(ad.TargetUrl);
            }
            else
            {
                context.Response.Redirect("http://www.arthurgraus.nl");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}